import React, {useMemo} from 'react'
import { InbizGraph } from 'inbiz-graph';
import Cookies from 'js-cookie';
import {h5Utils, InbizIcon } from '@inbiz/utils';
import { GlobalRegistry } from '@inbiz/core';
import { useSearchUIState } from '../../../../store/hooks/useSearchUIState';
import { useJumpResult } from '../../../../store/hooks/useJumpResult';
import { useSearchUIDispatch } from '../../../../store/hooks/useSearchUIDispatch';
import { useConfigEventsApi } from '../../../../store/hooks/useSearchPropsState';
import './index.less'
export default function App(props) {
  const {closeIcon, customWidth, customHeight,svgBoxId, fullModalVisible} = props
  const { keyword, showGraph } = useSearchUIState();
  const updateUIState = useSearchUIDispatch();
  const onJumpResult = useJumpResult();
  const { configEvents } = useConfigEventsApi();
  
  const langs = {
    'zh-cn': 'zh-CN',
    'en-us':'en-US',
    'ja': 'ja'
  }
  const getlangs = () => {
    const langType = GlobalRegistry.getDesignerLanguage() as 'zh-cn' | 'en-us' | 'ja'
    return langs[langType]
  }
  
  const InbizGraphProps = useMemo(() => {
    const options = {
      width: customWidth??600,
      height: customHeight??460,
      graphUrl: `/search/IndexSearch/GetAtlasData?token=${Cookies.get('token')}`,
      params: {
        anchor: keyword || '',
        step: 2,
        type: 'entity',
        offset: 0,
      },
      svgBoxId,
      lang: getlangs(),
      EDOC2_URL: '/preview.html?fileid=',
      visible: fullModalVisible,
      optEvent: {
        searchDoc: (data: any) => {
          onJumpResult(data?.name || '', data?.name ? [data.name] : []);
          updateUIState({
            keyword: data?.name || '',
            keywords: [data?.name || ''],
            showGraph: false,
          });
        },
      },
    };
    return (showGraph && configEvents.current.onInbizGraphInit?.(options)) || options;
  }, [showGraph, customWidth, customHeight, fullModalVisible, svgBoxId]);
  return (
    <div className="search-text-graph-inline" 
    onClick={() => {
      h5Utils.inbizPageEvent.emit(props.controlId, true);
    }}>
      <InbizGraph {...InbizGraphProps} />
      {closeIcon && <span className="close-btn" onClick={() => updateUIState({ showGraph: false, showSearchResultPanel: true, })}>
        <InbizIcon type="icon-guanbi-yeqian" />
      </span>}
    </div>
  )
}
